package com.dfxy.blog.listener;

import com.dfxy.blog.dao.UserDao;
import com.dfxy.blog.entity.User;
import com.dfxy.blog.util.DBUtil;
import com.dfxy.blog.window.MainWindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;

public class LogInActionListener implements ActionListener {

    private JTextField textFieldName;
    private JTextField textFieldPassword;

    private Connection con;
    private UserDao userDao;

    private Component parentComponent;

    private JFrame logInWindow;
    private JFrame mainWindow;

    public LogInActionListener(JTextField textFieldName, JTextField textFieldPassword, Connection con, UserDao userDao, Component parentComponent) {
        this.textFieldName = textFieldName;
        this.textFieldPassword = textFieldPassword;
        this.con = con;
        this.userDao = userDao;
        this.parentComponent = parentComponent;
    }

    public LogInActionListener(JTextField textFieldName, JTextField textFieldPassword, Connection con, UserDao userDao, Component parentComponent, JFrame logInWindow) {
        this.textFieldName = textFieldName;
        this.textFieldPassword = textFieldPassword;
        this.con = con;
        this.userDao = userDao;
        this.parentComponent = parentComponent;
        this.logInWindow = logInWindow;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            User logInResultUser = userDao.logIn(con, new User(textFieldName.getText(), textFieldPassword.getText(), null));
            if (logInResultUser == null) {
                JOptionPane.showMessageDialog(parentComponent, "用户名或密码错误");
            } else {
                logInWindow.setVisible(false);
                DBUtil.closeConnection(con);

                if (mainWindow == null) {
                    mainWindow = new MainWindow(textFieldName.getText(), logInResultUser.getLastLogInTime());
                }

                mainWindow.setVisible(true);
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
    }
}
